/*ParallelPlatform Project - A web platform to distribute and share knowledge
Copyright (C) 2011  Daniel Guerrero Martinez & Sergio Rodriguez Lumley

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.*/
GENTICS.Aloha.Resources = new GENTICS.Aloha.Plugin("com.parallelplatform.aloha.plugins.Resources");
GENTICS.Aloha.Resources.languages = ["en", "es"];
GENTICS.Aloha.Resources.button = null;

GENTICS.Aloha.Resources.init = function () {
	this.initButtons();

	$.each( $("div .multiImg") , function(){
		$(this).unbind();
		$(this).next().remove();
		$(this).click( GENTICS.Aloha.Resources.adminMuliImg );
	});
	
	GENTICS.Aloha.EventRegistry.subscribe(GENTICS.Aloha, "selectionChanged", function (e, params) {
		if( GENTICS.Aloha.activeEditable.getId() == 'title' )
			GENTICS.Aloha.Resources.button.hide();
		else
			GENTICS.Aloha.Resources.button.show();
			
		GENTICS.Aloha.FloatingMenu.doLayout();
	});

};

GENTICS.Aloha.Resources.initButtons = function () {
	var that = this;
	button = new GENTICS.Aloha.ui.Button({
							iconClass : "GENTICS_button multiImgBtn",
							size : "small",
							//label: that.i18n("button.addResources"),
							onclick : function () {
								var range = GENTICS.Aloha.Selection.getRangeObject();
								if( range.isCollapsed() ){
										
									var newMultiImg = jQuery('<div class="multiImgWrapper"><div class="multiImg" contenteditable="false"></div></div>');
									GENTICS.Utils.Dom.insertIntoDOM(newMultiImg, range, jQuery(GENTICS.Aloha.activeEditable.obj));
									newMultiImg.find(".multiImg").click( GENTICS.Aloha.Resources.adminMuliImg );
									newMultiImg.find(".multiImg").click();
									
								}
							},
							tooltip : that.i18n("button.addResources.tooltip"),
							toggle : false
						});
	
	GENTICS.Aloha.FloatingMenu.addButton("GENTICS.Aloha.continuoustext", button, GENTICS.Aloha.i18n(GENTICS.Aloha, "floatingmenu.tab.insert"), 1);
	GENTICS.Aloha.Resources.button = button;
}

GENTICS.Aloha.Resources.uploadFile = function(form,success) {
	var options = { 
		dataType: "json",
		success: function (response, status, xhr, $form){
			if( response.success )
				success(response);
    		else
    			alert(response.error);
		},
		
		beforeSubmit: function (formData, jqForm, options){
			if (jqForm.find("input[type=file]").val() == "" ){
				alert(GENTICS.Aloha.Resources.i18n("message.uploadFailure"));
				return false;
			}
			return true;
		},
	};
	form.ajaxSubmit(options);
}

GENTICS.Aloha.Resources.adminMuliImg = function () {
	var that = GENTICS.Aloha.Resources
	var multiImg = $(this);
	GENTICS.Aloha.Resources.editMultiImg = multiImg
	
	var dialog = jQuery('<div class="totalPanel"><div id="dialogMultiImg" class="dialogPanel">'+
				'<p title="'+that.i18n("p.imagesInfoTitle")+'">'+ that.i18n("p.imagesInfo") +'</p>'+
               '<div class="subMenu"><input type="button" name="ok" value="'+ that.i18n("input.dialogOk") +'">'+
               '</div>'+
               '</div></div>');
    
	element = jQuery('<form class="uploadImg" action="/resources/" method="post" enctype="multipart/form-data">'+
				 	'<input class="fileToUpload" type="file" name="file" accept="image/jpeg,image/png,image/gif" />'+
				 '</form>');			 
	
	$(element).find("input").change( function(event) {
		event.preventDefault();
		if( $("#dialogMultiImg").find("img").length < 8 ){
			GENTICS.Aloha.Resources.uploadFile($(this).parent(),function(response){
				if (response.success){
					if( $("#dialogMultiImg").find("img").length >= 7 )
						$("form.uploadImg").fadeOut("fast",function(){
							GENTICS.Aloha.Resources.configNewElement(box, response.url);
						});
					else
						GENTICS.Aloha.Resources.configNewElement(box, response.url);
				}else
					alert(response.errors);
			});
		}
	});

	var box = jQuery("<div></div>");
	box.append(element);
	$.each( $(multiImg).find("img") , function (){
		GENTICS.Aloha.Resources.configNewElement(box, $(this).attr("src") );
	});
	
	var animate = jQuery('<input class=dialogButtonPlpanim type="button" value="'+that.i18n("input.animate")+'"/>');
	animate.click( GENTICS.Aloha.Resources.editAnimateInit );
	
	var uploadAnimation = jQuery(
			'<p>'+that.i18n("p.uploadSwf")+'</p>'+
			'<form class="dialogButtonSwf" action="/resources/" method="post" enctype="multipart/form-data">'+
	 		'<input type="file" name="file" accept="swf" />'+
		 	'</form>');
	
	$(uploadAnimation).find("input").change( function(event) {
		event.preventDefault();
		//console.log("Entrando aquiiiii");
		//console.log($(".dialogButtonSwf"));
		
		GENTICS.Aloha.Resources.uploadFile($(".dialogButtonSwf"),function(response){
				//console.log("Recibidooooo");
				//console.log(response);
			if( response.success ){
				$(GENTICS.Aloha.Resources.editMultiImg).attr("animate", response.url);
				GENTICS.Aloha.Resources.showTypesAnimate();
			}else
				alert( that.i18n("message.uploadFailure") );
		});
	});
	
	var addAnimation = jQuery('<div class="dialogAddAnimation"><div><span></span></div></div>');
							  
	addAnimation.append(animate);
	addAnimation.append(uploadAnimation);
	
	dialog.find("#dialogMultiImg").append(box);
	dialog.find("#dialogMultiImg").append(addAnimation);
	
	// Closing multiImage dialog
	dialog.find('input[name=ok]').click( function(){
		//console.log("ok")
		var dialog = $("#dialogMultiImg");
		var close = true;
		if(dialog.find("img").length > 0 ){
			GENTICS.Aloha.Resources.editMultiImg.empty();
			$.each( dialog.find("img") , function (){
				//console.log("add img")
				GENTICS.Aloha.Resources.editMultiImg.append(this);
			});
		}else{
			if( $(GENTICS.Aloha.Resources.editMultiImg).attr("animate") != undefined ){
				var confirmed = confirm(GENTICS.Aloha.Resources.i18n("message.deleteMultiImgWithAnimation"));
    			if(confirmed){
    				GENTICS.Aloha.Resources.editMultiImg.remove();
    			}else{
    				close = false;
    			}
			}else{
				GENTICS.Aloha.Resources.editMultiImg.remove();
			}
		}
		
		if(close) $(".totalPanel").fadeOut("fast", function(){ $(this).remove(); });
	});
	
	$(addAnimation).find("p").click( function(){
		$(addAnimation).find(".dialogButtonSwf").slideDown('slow');
	});
	$(addAnimation).find(".dialogButtonSwf").css('display', 'none');
	
	$("body").append(dialog);
	dialog.css("display", "none");
	dialog.fadeIn("fast");
	
	if( $("#dialogMultiImg").find("img").length >= 8 )
		$("form.uploadImg").css('display','none');
	
	GENTICS.Aloha.Resources.showTypesAnimate();
}

GENTICS.Aloha.Resources.showTypesAnimate = function(){
	var that = GENTICS.Aloha.Resources
	var ext= ""
	var buttonText= that.i18n("input.animateWithNoAnimation")
	if( $(GENTICS.Aloha.Resources.editMultiImg).attr("animate") != undefined ){
		$(GENTICS.Aloha.Resources.editMultiImg).addClass('withanimation');
		var ext = String($(GENTICS.Aloha.Resources.editMultiImg).attr("animate")).split('.')
		ext = ext[ext.length-1].toLowerCase()
		switch( ext ){
		case "swf":
			buttonText= that.i18n("input.animateWithSwf");
			break;
		case "plpanim":
			buttonText= that.i18n("input.animateWithPlpanim");
			break;
		default: // Ot has an animation, but we do not recognize the extension
			buttonText= that.i18n("input.animateWithAnAnimation");
			break;
		}
	}else{
		$(GENTICS.Aloha.Resources.editMultiImg).removeClass('withanimation')
	}
	// First we remove all classes, then we put the class of the extension and we put the text
	$(".dialogAddAnimation").find("span").removeClass().addClass(ext).html(ext);
	// We set the value of the button to add animation
	$(".dialogAddAnimation").find("input.dialogButtonPlpanim").val(buttonText);
}


GENTICS.Aloha.Resources.configNewElement = function (box,url) {
	newElement = jQuery('<div class="dialogImgElement">'+
						'<span class="remove"></span>'+
						'<span class="before"></span>'+
						'<span class="after"></span>'+
						'<img src="'+url+'" /></div>');
	
	$(box).find(".uploadImg").before(newElement);
	
	newElement.find("span").css('display','none');

	newElement.find(".remove").click( function (event) {
		$(this).parent().hide("slow",function(){
			$(this).remove();
			$("form.uploadImg").fadeIn('slow');
		});
	});
	
	newElement.find(".after").click( function (event) {
		if( $(this).parent().next().is("div") ){
			$(this).parent().fadeOut("slow",function(){
					$(this).next().after($(this));
					$(this).fadeIn("slow");
			});
		}
	});
	
	newElement.find(".before").click( function (event) {
		if( $(this).parent().prev().is('div') ){
			$(this).parent().fadeOut("slow",function(){
					$(this).prev().before($(this));
					$(this).fadeIn("slow");
			});
		}
	});
	
	newElement.mouseenter(function(){
		if( $(this).prev().is('div') )
			$(this).find("span.before").fadeIn('fast')
		if( $(this).next().is("div") )
			$(this).find("span.after").fadeIn('fast')
		$(this).find("span.remove").fadeIn('fast')
	});
	
	newElement.mouseleave(function(){
		$(this).find("span").fadeOut('fast');
	});
	

}

GENTICS.Aloha.Resources.editAnimateInit = function(){
	
	var beforeDialog = $(".totalPanel");
	
	var animate = $(GENTICS.Aloha.Resources.editMultiImg).attr("animate");
	var ext = String(animate).split('.');
	if( ext[ext.length-1].toLowerCase() != "plpanim" )
		animate = "";
	
	var param = "";
	if ( animate && animate != "" )
		param += "file="+animate+"&";
	param += "author="+$("span.login").html().replace(/\s*/g, "")+"&"; // This is a temporary solution, the correct way would be to ask the server who am I
	param += "callee=/resources/";
	
	var flash = jQuery('<div class="totalPanel"><div class="dialogPanel">'+
			   '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="700" height="500" id="online_editor" align="middle">'+
               '<param name="allowScriptAccess" value="sameDomain" />'+
               '<param name="allowFullScreen" value="false" />'+
               '<param name="flashVars" value="'+param+'" />'+
               '<param name="movie" value="/media/flash/online_editor.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />'+
               '<embed src="/media/flash/online_editor.swf" quality="high" bgcolor="#ffffff" width="700" height="500" name="online_editor" align="middle" '+
               'flashVars="'+param+'" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer_es" />'+
               '</object>'+
               '<div class="subMenu"><input type="button" name="save" value="'+ GENTICS.Aloha.Resources.i18n("input.dialogSave") +'">'+
               '</div></div></div>');
    
    flash.find('input[name=save]').click( function(){
    	$.getJSON('/resources/last/',function(data){
    		if( data.success ){
    			$(GENTICS.Aloha.Resources.editMultiImg).attr("animate", data.lastupload);
    			//$(".totalPanel").fadeOut("fast", function(){ $(this).remove(); });
    			//$(GENTICS.Aloha.Resources.editMultiImg).addClass('withanimation')
    			$(".totalPanel").remove();
    			beforeDialog.addClass("totalPanel");
    			beforeDialog.css("display","block");
    			GENTICS.Aloha.Resources.showTypesAnimate();
    		}else{
    			var confirmed = confirm(GENTICS.Aloha.Resources.i18n("message.animationNotFound"));
    			if(confirmed){
    				//$(".totalPanel").fadeOut("fast", function(){ $(this).remove(); });
    				//$(GENTICS.Aloha.Resources.editMultiImg).removeClass('withanimation')
    				$(".totalPanel").remove();
					beforeDialog.addClass("totalPanel");
					beforeDialog.css("display","block"); 
    			}
    		}
    	});
    });
    
    //beforeDialog.css("display","none");
    beforeDialog.removeClass();
    $("body").append(flash);
    //flash.css("display", "none");
    //flash.fadeIn("fast");
     
}

 